#include"Socket.hpp"
#include"agreement.pb.h"

#include<sstream>
#include<string>

using namespace SocketModule;

int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        cout<<"client serverip serverport"<<endl;
        return 1;
    }
    SockPtr sock=make_shared<TcpSocket>();
    sock->BuildSocket(SockType::ORDINARY_SOCK);

    uint16_t server_port=stoi(argv[2]);

    sock->Connect(ntohl(inet_addr(argv[1])),server_port);

    while(true)
    {
        cout<<"client# ";
        

        string in;
        getline(cin,in);

        stringstream ss(in);
        int left=0;
        char opera=0;
        int right=0;
        ss>>left;
        ss>>opera;
        ss>>right;
        //构建请求
        Request requ1;
        requ1.set__left(left);
        requ1.set__operator(opera);
        requ1.set__right(right);

        Request requ2;
        requ2.set__left(left);
        requ2.set__operator(opera);
        requ2.set__right(right);

        Request requ3;
        requ3.set__left(left);
        requ3.set__operator(opera);
        requ3.set__right(right);

        string out1;
        string out2;
        string out3;

        //序列化
        requ1.SerializeToString(&out1);
        requ2.SerializeToString(&out2);
        requ3.SerializeToString(&out3);

        

        //添加报头
        string info1=to_string(out1.size())+"\r\n";
        info1+=out1;
        string info2=to_string(out2.size())+"\r\n";
        info2+=out2; 
        string info3=to_string(out3.size())+"\r\n";
        info3+=out3;


        string info=info1+info2+info3;
        sock->Send(info);

        in.clear();
        sock->Recv(in);
        cout<<in<<endl;
        //去除报头
        int pos=in.find("\r\n");
        in=in.substr(pos+2);

        //反序列化
        Response resp;
        resp.ParseFromString(in);
        cout<<"结果："<<resp._result()<<"结果是否可信: "<< resp._is_trust()<<endl;
    }
    return 0;
}